// socket.io
const express = require('express')
const router = express.Router()
const http = require('http');
const socketIO = require('socket.io');
let server = http.createServer(app);
let io = socketIO(server, {
  cors: {
    origin: "http://127.0.0.1:3000",
    methods: ["GET", "POST"],
    credentials: true,
    allowEIO3: true
  },
  transport: ['websocket']
});
io.on('connection', function (socket) {
  socket.emit('fresh-message', chatList);
  socket.on('send-message', (user, message) => {
    const createTime = moment().format('YYYY-MM-DD HH:mm:ss');
    chatList.push({
      user,
      message,
      createTime,
    });
    socket.emit('fresh-message', chatList);
  });
  // 接受到消息时触发
  socket.on('message', function (data) {
    console.log('服务端收到: ', + data);
    socket.send('发送至客户端,' + data);
  });
  // 发生错误时触发
  socket.io('error', function (err) {
    console.log(err);
  })
});


module.exports = io
